﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

namespace Website.Data
{
    public class DataAccess
    {
        static public System.Data.SqlClient.SqlConnection SqlConnection(string key)
        {
            string _SqlConnectionKey;
            _SqlConnectionKey = string.Format("{0}_OltpConStr", Environment.MachineName);

            string _SqlConnectionString;
            _SqlConnectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;

            if (string.IsNullOrEmpty(_SqlConnectionString))
                throw new System.NullReferenceException(_SqlConnectionKey);

            System.Data.SqlClient.SqlConnection _SqlConnection;
            _SqlConnection = new System.Data.SqlClient.SqlConnection();
            _SqlConnection.ConnectionString = _SqlConnectionString;

            // open connection

            try
            {
                _SqlConnection.Open();
                if (_SqlConnection.State != ConnectionState.Open)
                    throw new SqlConnectionStateNotOpen(_SqlConnection.State.ToString(), null);
            }
            catch (Exception ex)
            {
                throw new SqlConnectionErrorOnOpen(_SqlConnectionKey, ex);
            }

            return _SqlConnection;
        }

        [Serializable]
        public class SqlConnectionStateNotOpen : System.ApplicationException
        {
            public SqlConnectionStateNotOpen(string msg, Exception ex)
                : base(msg, ex)
            {
            }
        }

        [Serializable]
        public class SqlConnectionErrorOnOpen : System.ApplicationException
        {
            public SqlConnectionErrorOnOpen(string msg, Exception ex)
                : base(msg, ex)
            {
            }
        }
    }
}
